package org.zoomdev.zoom.dao.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.configs.Query;
import org.zoomdev.zoom.dao.configs.Where;
import org.zoomdev.zoom.dao.handler.ResultSetHandler;
import org.zoomdev.zoom.dao.modules.CoreDaoModule;
import org.zoomdev.zoom.dao.utils.LogUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public final class QueryExecutor {

    private static final Logger log = LoggerFactory.getLogger(CoreDaoModule.NAME);

    private QueryExecutor() {
    }


    public static Object handle(SqlConfig cfg, ResultSetHandler handler) {
        Query query = cfg.getQuery();
        Where where = cfg.getWhere();
        query.prepare(cfg);
        String sql = query.build(cfg, where);
        if (CoreDaoModule.logSql) {
            log.info(LogUtils.getSql(sql, query.getParameterValues(where)));
        }
        Connection conn = cfg.openConnection();
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            query.setParameter(where, stmt);
            try (ResultSet rs = stmt.executeQuery()) {
                return handler.fromResultSet(cfg, rs);
            }
        } catch (SQLException e) {
            throw new DaoException("执行query失败:" + LogUtils.getSql(sql, query.getParameterValues(where)), e);
        }

    }


}
